<template>
  <!-- 巡检列表 -- 添加/编辑-->
  <div class="page-operate">
    <!-- 位置模块 -->
    <HeadTop></HeadTop>
    <div class="page-head">
      <span class="operate-text">{{title}}</span>
      <div class="operate-box">
        <button @click="submitForm('myForm')" v-show="editAble" class="submit">提交</button>
        <button @click="back()">关闭</button>
      </div>
    </div>
    <div class="content-area">
      <div class="main-content form-edit">
        <div class="page-form">
          <el-form class="my-form my-form-600" ref="myForm" :rules=rules :model="myForm" label-width="150px"
                   size="medium">
            <el-form-item label="电梯注册代码:" class="hasSearchInp" required prop="registerCode">
              <el-input v-model="myForm.registerCode" class="input-has-search" readonly>
                <el-button slot="append" size="mini" icon="el-icon-search" @click="showDialogTable"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="电梯名称:" required>
              <el-input v-model="myForm.elevatorName" readonly></el-input>
            </el-form-item>
            <el-form-item label="巡检人员:" class="hasSearchInp">
              <el-select v-model="myForm.adminId" placeholder="请选择巡检人员" clearable>
                <el-option v-for="(item,key,index) in examineUserArr" :key="item.userid" :label="item.username"
                           :value="item.userid"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="过期日期:" required :class="invalidDateErrorShow?'is-error':''" v-show="adminIsShow">
              <el-date-picker v-model="myForm.invalidDate" align="right" type="date" placeholder="请选择日期"
                              @change="invalidDateChange" value-format='yyyy-MM-dd HH:mm:ss'>
              </el-date-picker>
              <div class="el-form-item__error" v-show="invalidDateErrorShow">{{invalidDateError}}</div>
            </el-form-item>
            <el-form-item label="备注:">
              <el-input type="textarea" class="my-area" placeholder="填写备注信息" v-model="myForm.brief"></el-input>
            </el-form-item>
            <el-form-item label="巡查类型:" required>
              <el-checkbox-group v-model="patrolTypeIdArr" class="patrolType">
                <el-checkbox v-for="(item,key, index) in examineArr" :key="item.id" :label=item.examineid
                             name='examine'>{{item.name}}
                </el-checkbox>
              </el-checkbox-group>
              <div class="el-form-item__error" v-show="patrolTypeErrorShow">请选择巡查类型</div>
            </el-form-item>
          </el-form>
        </div>
        <v-dialogTable :dialogTableObj="dialogTableObj" v-on:getChildPageNo="searchByChildPageNo"
                       v-on:getChildPageSize="searchByChildPageSize" ref="dialogTable">
          <div slot="searchDiv">
            <div class="search-msg">
              <div class="search-msg-input">
                <el-form class="my-form my-form-600" ref="dialogTableObj.dialogForm" :model="dialogTableObj.dialogForm"
                         label-width="80px" size="medium">
                  <el-form-item label="查询信息:">
                    <el-input v-model="dialogTableObj.dialogForm.registerCode" placeholder="请输入注册代码"
                              @click="dialogSearch"></el-input>
                  </el-form-item>
                </el-form>
              </div>
              <button @click="dialogSearch">查询</button>
            </div>
          </div>
          <div>
            <el-table-column fixed="right" align="center" label="查找带回" :min-width="100">
              <template slot-scope="scope">
                <div class="check-position" @click="clickCheckBox(scope.row)">
                  <!--<el-checkbox>{{scope.row.name}}</el-checkbox>-->
                  <el-radio v-model="selectRadio" :label="scope.row.id">&nbsp;</el-radio>
                </div>
              </template>
            </el-table-column>
          </div>
        </v-dialogTable>
      </div>
    </div>
  </div>
</template>
<style lang="scss" type="text/scss">
  @import '../../../../style/entry/components/pageChildCommon';
  .patrolType {
    width: 600px !important;
  }

  .patrolType .el-checkbox {
    margin-left: 30px;
  }
</style>
<script>
  import com from "../../../../js/common"
  import DialogTable from "../../../../components/dialogTable/dialogTable"
  import HeadTop from "../../../../components/head-top/head-top"
  import {getEleList, getExamineUser, getExamineType, addExaminePlain} from '@/api/getData'
  import moment from 'moment'

  export default {
    components: {
      'v-dialogTable': DialogTable,
      HeadTop
    },
    data() {
      return {
        radio: '1',
        selectRadio: '',
        title: '发布巡检任务',
        type: 'add',
        examineRecordId: '',
        examineRecordCode: '',
        adminName: '',
        editAble: true,
        adminIsShow: false,
        invalidDateError: '', // 过期时间选择的校验
        invalidDateErrorShow: false, //过期时间校验的错误提示，默认不显示
        patrolTypeErrorShow: false, //巡查类型是否为空的校验提示，默认不显示
        myForm: {
          elevatorName: '',
          registerCode: '',
          patrolTypeId: '',
          adminId: null,
          brief: '',
          invalidDate: '',
          elevatorId: '',
        },
        rules: {
          registerCode: [
            {required: true, message: '请选择电梯注册码'}
          ],
          elevatorName: [
            {required: true, message: '请选择电梯名称'}
          ]
        },
        examine: [],
        examineArr: [],
        examineUserArr: [],
        patrolTypeIdArr: [],
        // 选择电梯弹窗表格组件数据
        dialogTableObj: {
          // 组件标题
          title: '查找带回',
          // 表格数据
          tableData: [],
          // 表格标题
          tableColumns: [
            {
              title: '序号',
              width: '60',
              attributeName: 'index'
            },
            {
              title: '注册代码',
              width: '140',
              attributeName: 'registerCode'
            },
            {
              title: '电梯名称',
              width: '80',
              attributeName: 'argsName'
            }
          ],
          // 翻页的数据
          pageObj: {
            // 每页分为几条数据
            pageSize: 5,
            // 总共多少数据
            pageNum: 0,
            // 当前页
            pageNo: 1,
            hideReload: true,
          },
          dialogForm: {
            registerCode: ''
          },
          dialogTableVisible: false,
        }
      };
    },
    watch: {
      myForm: {
        handler: function (val, oldval) {
          return
        },
        deep: true
      },
      'myForm.adminId': function (cl, ol) {
        this.adminIsShow = cl != '' ? true : false;
      }
    },

    // 获取添加操作所需数据
    mounted() {
      // 获取巡查类型数据
      this.getExamineItemsData();
      let departmentId = com.getStore('departmentId');
      this.chooseExamineUser(departmentId);
      this.chooseEleByCode();
    },
    methods: {
      // 获取电梯基本数据
      chooseEleByCode() {
        getEleList({
          pageNo: this.dialogTableObj.pageObj.pageNo,
          pageSize: this.dialogTableObj.pageObj.pageSize,
          condition: this.dialogTableObj.dialogForm,
        }).then((data) => {
          let startPage = (this.dialogTableObj.pageObj.pageNo - 1) * this.dialogTableObj.pageObj.pageSize;
          let info = data.data.data;
          let infoArr = info.data;
          infoArr.forEach(function (i, t) {
            i.index = startPage + t + 1;
          })
          this.dialogTableObj.tableData = infoArr;
          this.dialogTableObj.pageObj.pageNum = info.totalRecord;
        }).catch((err) => {
          this.$message.error('查询电梯基本数据失败')
        })
      },

      // 获取巡查人员数据
      chooseExamineUser(departmentId) {
        getExamineUser({}).then((data) => {
          let info = data.data.data;
          let examineUserArr = [];
          info.forEach(function (i) {
            examineUserArr.push({'username': i.realName, 'userid': i.id});
          })
          this.examine = this.examineUserArr = examineUserArr;
        }).catch((err) => {
          this.$message.error('查询巡检人员数据失败')
        })
      },

      // 获取巡查类型数据
      getExamineItemsData() {
        getExamineType({
          pageNo: 1,
          pageSize: 1000,
        }).then((data) => {
          let info = data.data.data.data;
          let examineArr = []
          info.forEach(function (i) {
            examineArr.push({'examineid': i.id, 'name': i.name, 'checked': false})
          })
          this.examineArr = examineArr;
        }).catch((err) => {
          this.$message.error('查询巡检类型数据失败 ')
        })
      },

      // 创建/修改表单数据的校验
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            let str = '';
            let nowTime = Date.parse(new Date());
            this.invalidDateErrorShow = false;
            this.patrolTypeErrorShow = false;
            if (this.myForm.adminId === null || this.myForm.adminId === '') {
              this.patrolTypeErrorShow = false;
            } else {
              this.invalidDateChange(this.myForm.invalidDate);
            }
            if (this.patrolTypeIdArr.length > 0) {
              this.myForm.patrolTypeId = this.patrolTypeIdArr.join('|');
              this.patrolTypeErrorShow = false;
            } else {
              this.patrolTypeErrorShow = true;
            }
            if (!this.patrolTypeErrorShow && !this.invalidDateErrorShow) {
              if (this.myForm.adminId == '' || this.myForm.adminId == null) {
                delete this.myForm['invalidDate']
              }
              this.addExamine();
            }
          } else {
            return false;
          }
        });
      },

      // 发布巡检任务
      addExamine() {
        addExaminePlain(this.myForm).then((res) => {
          com.mask()
          this.$message.success({
            message: '操作成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$router.push('/manage/examineMgr/examineLists')
            }
          })
        }).catch((err) => {
          this.$message.error('操作失败： ' + err.data.data)
        })
      },

      // 选择过期时间时的校验：1.不能为空 2.不能大与当前时间
      invalidDateChange(val) {
        let nowTime = Date.parse(new Date());
        if(!val){
          this.invalidDateErrorShow = true;
          this.invalidDateError = '请选择过期时间';
        } else if (moment(val).isBefore(nowTime)) {
          this.invalidDateErrorShow = true
          this.invalidDateError = '过期时间应大于当前时间';
        } else {
          this.invalidDateErrorShow = false;
        }
      },

      // 点击对话框查询按钮 调用按注册码查询电梯信息接口
      dialogSearch() {
        this.chooseEleByCode();
      },

      // 表格弹窗所需函数方法
      showDialogTable() {
        this.dialogTableObj.dialogTableVisible = true;
      },

      // 表格弹窗换页
      searchByChildPageNo(val) {
        this.dialogTableObj.pageObj.pageNo = val;
        this.chooseEleByCode();
      },

      // 切换表格弹窗每页数据展示条目
      searchByChildPageSize(val) {
        this.dialogTableObj.pageObj.pageSize = val;
        this.chooseEleByCode();
      },

      // 表格弹窗中选定电梯
      clickCheckBox(row) { // 点击选择
        this.selectRadio = row.id
        this.myForm.registerCode = row.registerCode;
        this.myForm.elevatorName = row.argsName;
        this.myForm.elevatorId = row.id;
        this.dialogTableObj.dialogTableVisible = false;
        this.dialogTableObj.dialogForm.registerCode = '';
      },

      // 返回上一级
      back() {
        this.$router.go(-1);
      },
    }
  };
</script>
